import unittest

from tinydb.sql.parser.parser import query_parse


class TestParser(unittest.TestCase):
    def test_query_parse(self):
        q1 = query_parse('select a, b from t1')
        self.assertEqual(str(q1), "<Select> targets=[<Identifier> parts='a', <Identifier> parts='b'] from_table=<Identifier> parts='t1' where=None group_by=None order_by=None")
        q2 = query_parse('select a, b from t1 where a > c')
        self.assertEqual(str(q2), "<Select> targets=[<Identifier> parts='a', <Identifier> parts='b'] from_table=<Identifier> parts='t1' where=<BinaryOperation> op='>' args=[<Identifier> parts='a', <Identifier> parts='c'] group_by=None order_by=None")
        q3 = query_parse('select a, b from t1 where a > b order by b')
        self.assertEqual(str(q3), "<Select> targets=[<Identifier> parts='a', <Identifier> parts='b'] from_table=<Identifier> parts='t1' where=<BinaryOperation> op='>' args=[<Identifier> parts='a', <Identifier> parts='b'] group_by=None order_by=<OrderBy> column=<Identifier> parts='b' direction='ASC'")
        q4 = query_parse('select a, count(a) from t1 group by b')
        self.assertEqual(str(q4), "<Select> targets=[<Identifier> parts='a', <FunctionOperation> op='count' args=[<Identifier> parts='a']] from_table=<Identifier> parts='t1' where=None group_by=[<Identifier> parts='b'] order_by=None")

        q5 = query_parse('select a, b from t1 where t1.a > t1.c')
        self.assertEqual(str(q5), "<Select> targets=[<Identifier> parts='a', <Identifier> parts='b'] from_table=<Identifier> parts='t1' where=<BinaryOperation> op='>' args=[<Identifier> parts='t1.a', <Identifier> parts='t1.c'] group_by=None order_by=None")
    
    def test_parse_update_stmt(self):
        q1 = query_parse('update t1 set a = 1 where a > 1')
        self.assertEqual(str(q1), "<Update> table=<Identifier> parts='t1' columns={<Identifier> parts='a': <Constant> value=1} where=<BinaryOperation> op='>' args=[<Identifier> parts='a', <Constant> value=1]")
    
    @unittest.expectedFailure
    def test_query_parse_fail(self):
        query_parse('select a, b from t1 order by b order by a')

if __name__ == '__main__':
    unittest.main()
